﻿//AcademicPlanner - course registration planning web app.
//Copyright (C) 2009  Boubacar Diallo

//This program is free software; you can redistribute it and/or
//modify it under the terms of the GNU General Public License
//as published by the Free Software Foundation; either version 2
//of the License, or (at your option) any later version.

//This program is distributed in the hope that it will be useful,
//but WITHOUT ANY WARRANTY; without even the implied warranty of
//MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//GNU General Public License for more details.

//You should have received a copy of the GNU General Public License
//along with this program; if not, write to the Free Software
//Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using AcademicPlanner.Presentation.Views.Programs;
using AcademicPlanner.Framework.Helpers;
using AcademicPlanner.Framework.Libraries.Mvc;
using AcademicPlanner.Domain;
using AcademicPlanner.Domain.Models;

namespace AcademicPlanner.Presentation.Controllers
{
	/// <summary>
	/// ProgramsController is the Mvc controller for requests
	/// under /Programs/* in the AcademicPlanner application
	/// web site.
	/// </summary>
	/// <since>1.0</since>
	[HandleError]
	public class ProgramsController : Controller
	{
		/// <summary>
		/// Displays a web page that lists all the academic programs
		/// in an academic plan.
		/// </summary>
		/// <param name="pId">The identifier of the academic plan in the system.</param>
		/// <returns>A Programs/List view in a InSection master page.</returns>
		/// <exception cref="T:System.Web.HttpException">
		/// Thrown with status code 404 if an academic plan with the given identifier does not exist
		/// in the system.
		/// </exception>
		/// <seealso cref="P:Application"/>
		/// <seealso cref="P:AcademicPlanner.Presentation.AcademicPlannerWebApp.DomainMaster"/>
		/// <seealso cref="P:AcademicPlanner.Domain.DomainMaster.Planning"/>
		/// <seealso cref="M:AcademicPlanner.Domain.Components.AcademicPlanningMngr.GetAcademicPlan(int)"/>
		/// <since>1.0</since>
		[AcceptVerbs(HttpVerbs.Get)]
		[RequireAuthentication]
		public ViewResult List(int pId)
		{
			var vViewModel = new ListProgramsViewModel();
			var vPlan = Application.DomainMaster
										.Planning.GetAcademicPlan(pId);

			if (vPlan != null)
			{
				vViewModel.AcademicPlanId = vPlan.EntityId;
				vViewModel.Programs = vPlan.Programs.ToList();
			}
			else
				throw new HttpException(404, Tr("The resource you are looking for was not found!"));

			return View("List", "InSection", vViewModel);
		}

		/// <summary>
		/// Handles the web request to create or update an academic program.
		/// </summary>
		/// <remarks>
		/// This methods reads the posted data and forwards the request
		/// to the domain layer. When <paramref name="pId"/> is <c>0</c>,
		/// creation is considered and a valid <paramref name="pParentId"/>
		/// is required; otherwise update is considered and <paramref name="pParentId"/>
		/// is ignored.
		/// </remarks>
		/// <param name="pId">The identifier of the academic program in the system.</param>
		/// <param name="pParentId">
		/// The identifier of the academic plan in the system the academic program belongs to.
		/// </param>
		/// <returns>Instructions to the browser in json format about the result of the action.</returns>
		/// <seealso cref="T:AcademicPlanner.Presentation.JsonResultData"/>
		/// <seealso cref="T:AcademicPlanner.Presentation.FormSubmission"/>
		/// <seealso cref="P:Application"/>
		/// <seealso cref="P:AcademicPlanner.Presentation.AcademicPlannerWebApp.DomainMaster"/>
		/// <seealso cref="P:AcademicPlanner.Domain.DomainMaster.Planning"/>
		/// <seealso cref="M:AcademicPlanner.Domain.Components.AcademicPlanningMngr.SaveNewProgram"/>
		/// <seealso cref="M:AcademicPlanner.Domain.Components.AcademicPlanningMngr.SaveProgram"/>
		/// <since>1.0</since>
		[AcceptVerbs(HttpVerbs.Post)]
		[AjaxOnly]
		public JsonResult Save(int pId, int pParentId)
		{
			int vIndex;
			var vResult = new JsonResultData();
			var vRequiredCourseIds = new List<int>();
			var vRecommendedCourseIds = new List<int>();

			Post.NamesPrefix = "";

			var vName = Post.GetAsString("Name");
			var vMinCredits = Post.GetAsNumber("MinimumCredits");
			var vRequiredCourses = Post.GetAsString("RequiredCourses");
			var vRecommendedCourses = Post.GetAsString("RecommendedCourses");
			var vRequiredCoursesStr = vRequiredCourses.Split(',');
			var vRecommendedCoursesStr = vRecommendedCourses.Split(',');

			for (var vI = 0; vI < vRequiredCoursesStr.Length; vI++)
			{
				vIndex = -1;
				if (int.TryParse(vRequiredCoursesStr[vI], out vIndex))
					vRequiredCourseIds.Add(vIndex);
			}
			for (var vI = 0; vI < vRecommendedCoursesStr.Length; vI++)
			{
				vIndex = -1;
				if (int.TryParse(vRecommendedCoursesStr[vI], out vIndex))
					vRecommendedCourseIds.Add(vIndex);
			}

			try
			{
				if (pId == 0)
				{
					Application.DomainMaster.Planning.SaveNewProgram(pParentId, vName, vMinCredits, 
																		vRequiredCourseIds, vRecommendedCourseIds);

					SessionHelper.AddSuccessStatusMessage(string.Format(Tr("Congratulations! The new program " +
						"was successfully added to your plan.")));
				}
				else
				{
					Application.DomainMaster.Planning.SaveProgram(pId, vName, vMinCredits,
																		vRequiredCourseIds, vRecommendedCourseIds);

					SessionHelper.AddSuccessStatusMessage(string.Format(Tr("Congratulations! Your program " +
						"information was successfully updated.")));
				}
				vResult.reload = true;
			}
			catch (InvalidModelPropertiesException vIx)
			{
				vResult.errors = Form.SummarizeErrors(vIx.Errors);
			}
			catch (NotCriticalDomainException vNcx)
			{
				SessionHelper.AddInfoStatusMessage(Tr(vNcx.Message));
				vResult.reload = true;
			}

			return Json(vResult);
		}

		/// <summary>
		/// Handles the web request to delete an academic program.
		/// </summary>
		/// <param name="pId">The identifier of the academic program in the system.</param>
		/// <returns>Instructions to the browser in json format about the result of the action.</returns>
		/// <seealso cref="T:AcademicPlanner.Presentation.JsonResultData"/>
		/// <seealso cref="P:Application"/>
		/// <seealso cref="P:AcademicPlanner.Presentation.AcademicPlannerWebApp.DomainMaster"/>
		/// <seealso cref="P:AcademicPlanner.Domain.DomainMaster.Planning"/>
		/// <seealso cref="M:AcademicPlanner.Domain.Components.AcademicPlanningMngr.DeleteProgram"/>
		/// <since>1.0</since>
		[AcceptVerbs(HttpVerbs.Post)]
		[AjaxOnly]
		public JsonResult Delete(int pId)
		{
			JsonResultData vResult = new JsonResultData();

			try
			{
				Application.DomainMaster.Planning.DeleteProgram(pId);

				SessionHelper.AddSuccessStatusMessage(string.Format(Tr("Congratulations! Your program " +
					"was successfully deleted.")));
				vResult.reload = true;
			}
			catch (NotCriticalDomainException vNcx)
			{
				SessionHelper.AddInfoStatusMessage(Tr(vNcx.Message));
				vResult.reload = true;
			}

			return Json(vResult);
		}
	}
}
